<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.pid" filterable placeholder="一级菜单" class="filter-item" @change="getList" clearable style="margin-left:5px;width:120px">
        <el-option
          v-for="item in pcate"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
      <el-input v-model="listQuery.keyword" placeholder="关键字搜索" style="width: 200px;margin-left:5px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" style="margin-left:5px" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>

      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>



      <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleMake">
        生成菜单
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" min-width="110px" align="center">
        <template slot-scope="{row}">
            <el-tag effect="plain" v-if="row.menu_type == 1">
              主菜单
            </el-tag>
          <el-tag type="success" effect="plain" v-else>
              子菜单
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="类型" min-width="110px" align="center">
        <template slot-scope="{row}">
          <el-tag effect="plain" v-if="row.type == 'click'">
            点击菜单
          </el-tag>
          <el-tag type="success" effect="plain" v-else>
            跳转菜单
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="名称" min-width="110px" align="center">
        <template slot-scope="{row}">
            <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="外链" min-width="110px" align="center" v-if="listQuery.type == 'view'">
        <template slot-scope="{row}">
          <span>{{ row.url }}</span>
        </template>
      </el-table-column>

      <!--      <el-table-column label="状态" class-name="status-col" min-width="100">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <el-radio-group v-model="row.publish" size="small" @change="changeStatus(row,$event)">-->
      <!--            <el-radio-button :label="1">使用</el-radio-button>-->
      <!--            <el-radio-button :label="2">禁用</el-radio-button>-->
      <!--          </el-radio-group>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="创建时间" class-name="status-col" min-width="100">
        <template slot-scope="{row}">
          {{ row.created_at }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
                     删除
            </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      :current-page="listQuery.page"
      @current-change="handlePageChange($event)"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="listQuery.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 100%;">
        <el-tabs v-model="temp.menu_type"  @tab-click="tabClick">
          <el-form-item label="菜单类型">
          <el-radio-group v-model="temp.type" class="filter-item" @change="temp.url = ''">
            <el-radio-button label="click">点击菜单</el-radio-button>
            <el-radio-button label="view">跳转菜单</el-radio-button>
          </el-radio-group>
            <span style="margin-left: 20px">
            <font color="#a9a9a9">在跳转菜单下不可添加子菜单</font>
            </span>
          </el-form-item>

          <el-form-item label="外链地址" v-if="temp.type == 'view'">
            <el-input v-model="temp.url"/>
          </el-form-item>


          <el-tab-pane label="主菜单" name="1" :disabled="dis_click">
            <el-card style="margin-top:10px">
              <el-divider>菜单设置</el-divider>
              <el-form-item label="菜单名称" prop="name">
                <el-input v-model="temp.name"/>
              </el-form-item>

              <el-form-item label="排序">
                <el-input v-model="temp.sort"/>
              </el-form-item>
            </el-card>
          </el-tab-pane>
          <el-tab-pane label="子菜单" name="2" :disabled="dis_click">
            <el-card style="margin-top:10px">
              <el-divider>菜单设置</el-divider>
            <el-form-item label="选择父菜单" >
              <el-select v-model="temp.pid" filterable placeholder="请选择" :disabled="dialogStatus == 'update'">
                <el-option
                  v-for="item in pcate"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="菜单名称" prop="name">
              <el-input v-model="temp.name"/>
            </el-form-item>

              <el-form-item label="排序">
                <el-input v-model="temp.sort"/>
              </el-form-item>
            </el-card>
          </el-tab-pane>
        </el-tabs>
        <!--        <el-form-item label="状态">-->
        <!--          <el-radio-group v-model="temp.publish" size="small">-->
        <!--            <el-radio-button :label=1>正常</el-radio-button>-->
        <!--            <el-radio-button :label=2>禁用</el-radio-button>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="Imp">-->
        <!--          <el-rate v-model="temp.importance" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" :max="3" style="margin-top:8px;" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="Remark">-->
        <!--          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {  getList, create, update, del, getPcate, makeMenu } from '@/api/we_menus'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import { cateAll } from '@/api/questions' // secondary package based on el-pagination


export default {
  name: 'WechatMenus',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        pid:'',
        keyword:'',
        menu_type:'1',
        cate_id:''
      },
      cates:[],
      pcate:[],
      setime:[],
      examtime:[],
      typeList:[
        {
          type:'1',
          label: '一级菜单'
        }, {
          type: '2',
          label: '二级菜单'
        }
      ],
      ipList:[
      ],
      showPcate:false,
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        name: '',
        pid:'',
        type:'view',
        url:'',
        sort:0,
        menu_type:'1',
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑分类',
        create: '创建分类'
      },
      dis_click:false,
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required' }],
        // timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        // title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    this.getPcate()
  },
  methods: {
    handleMake(){
      makeMenu().then(response => {
        this.$notify({
          message: response.msg,
          type: 'success',
          duration: 2000
        })
      })
    },
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        // Just to simulate the time of the request
        this.listLoading = false

      })
    },
    getTypeList(val){
      if(val == '1'){
        this.listQuery.pid = ''
        this.showPcate= false
      }else{
        this.showPcate=true
      }
      this.getList()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        pid:'',
        type:'',
        url:'',
        sort:0,
        menu_type:'1',
      }
    },
    handleCreate() {
      this.dis_click =false
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if(this.temp.menu_type == '1'){
            this.temp.pid = 0
          }
          if(this.temp.menu_type == '2' && this.temp.pid == '' ){
            this.$message('请先选择一级菜单')
            return ''
          }

          create(this.temp).then(response => {
            if(response.code == 200){
              this.dialogFormVisible = false
              this.$notify({
                message: response.msg,
                type: 'success',
                duration: 2000
              })
              this.getList()
              this.getPcate()
            }else{
              this.$notify.error({
                message: response.msg,
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.dis_click =true
      this.temp = Object.assign({}, row) // copy obj
      if(this.temp.menu_type == 1){
        this.temp.menu_type = '1'
      }
      if(this.temp.menu_type == 2){
        this.temp.menu_type = '2'
      }
      // if(row.type == 1){
      //   this.setime.push(row.sign_start)
      //   this.setime.push( row.sign_end)
      //   this.examtime.push(row.start_time)
      //   this.examtime.push(row.end_time)
      // }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          update(tempData).then(response => {
            if(response.code == 200){
              this.dialogFormVisible = false
              this.$notify({
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
              this.getPcate()
            }else{
              this.$notify.error({
                message: response.msg,
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm(
        '确定要删除该类吗(包含该类下所有子菜单)？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消', }).then(()=>{
        del(row.id).then(response => {
          if(response.code == 200){
            this.list.splice(index, 1)
            this.$notify({
              message: response.msg,
              type: 'success',
              duration: 2000
            })
          }else {
            this.$notify.error({
              message: response.msg,
              duration: 2000
            })
          }
        })
      }).catch(()=>{

      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    tabClick(tab, event) {
      // if(tab.name == 2){
      //   this.getPcate()
      // }
    },
    handleSizeChange(){
      this.getList()
    },
    handlePageChange(val){
      this.listQuery.page=val
      this.getList()
    },
    getPcate(){
      getPcate().then(response => {
        this.pcate = response.data
      })
    }
  }
}
</script>
